var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var wxpay = require('../../utils/pay.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: "",
    pid: "",
    doctor: "",
    time: "",
    nowtime: "",
    nowData: "",
    hospital: "",
    dates: "",
    weeks: "",
    shopprice: 0,
    selList: '',
    confirmOrder: {},
    curAddressData: null,//收货地址
    allCoupon: [],//所有能用的优惠券
    curCoupon: null,//当前优惠券
    hasPay: false,
    saveHidden: true,
    allSelect: true,
    noSelect: false,
    mallName: '',
    cartInfo: {},
    delBtnWidth: 120,    //删除按钮宽度单位（rpx）
    selList: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    var that = this;
    wx.setNavigationBarTitle({
      title: wx.getStorageSync('mallName')
    })
    that.CurentTime();
    that.CurentData();
    that.setData({
      pid: option.pid,
      doctor: option.doctor,
      shopprice: option.shopprice,
      dates: option.dates ? option.dates:"",
      weeks: option.weeks ? option.weeks:"",
      hospital: wx.getStorageSync('mallName')
    })
  },
  processImageHost: function (cart) {
    if (cart.StoreCartList.length > 0) {
      for (var i = 0; i < cart.StoreCartList[0].CartProductList.length; i++) {
        //主图
        cart.StoreCartList[0].CartProductList[i].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartProductList[i].OrderProductInfo.ShowImg;
        if (cart.StoreCartList[0].CartProductList[i].GiftList.length > 0) {
          for (var j = 0; j < cart.StoreCartList[0].CartProductList[i].GiftList.length; j++) {
            //赠品图片
            cart.StoreCartList[0].CartProductList[i].GiftList[j].ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartProductList[i].GiftList[j].ShowImg;
          }
        }
      }
      for (var i = 0; i < cart.StoreCartList[0].CartFullCutList.length; i++) {
        for (var j = 0; j < cart.StoreCartList[0].CartFullCutList[i].FullCutCartProductList.length; j++) {
          cart.StoreCartList[0].CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg;
        }
      }
      for (var i = 0; i < cart.StoreCartList[0].CartSuitList.length; i++) {
        for (var j = 0; j < cart.StoreCartList[0].CartSuitList[i].CartProductList.length; j++) {
          cart.StoreCartList[0].CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg;
        }
      }

    }
    return cart;

  },
  //提交订单
  createOrder: function (e) {
    var that = this;
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    if (!uid) {
      wx.showModal({
        title: '错误',
        content: '获取用户信息失败',
        showCancel: false
      })
      return;
    }
    if (that.data.curAddressData == null || !that.data.curAddressData.SAId) {
      wx.showModal({
        title: '请填写地址信息',
        content: '',
        showCancel: false
      });
      return;
    }
    wx.showLoading();
    var couponIdList = '';
    var remark = '备注'; // 备注信息
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: that.data.curAddressData.SAId,//配送地址id
      SelList: that.data.selList,//选中的购物车项键列表
      PayCreditCount: 0,//支付积分
      CouponIdList: couponIdList,//客户已经激活的优惠劵
      CouponSNList: '',//客户还未激活的优惠劵
      FullCut: that.data.confirmOrder.AllFullCut,//验证满减金额
      BuyerRemark: remark //备注
    }

    wx.request({
      url: app.globalData.host + '/api/order/SubmitOrderV2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '错误',
            content: res.data.Message,
            showCancel: false
          })
          return;
        }

        // 下单成功，跳转到支付界面
        var oid = res.data.Data;
        wxpay.wxpay(app, oid, "/pages/order-list/index");
        return;
        // 下单成功，跳转到订单管理界面
        // wx.redirectTo({
        //   url: "/pages/order-list/index?t=1"
        // });
      }
    })
  },
  // 获取当前年月
  CurentData: function () {
    var that = this;
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var clock = year + "-";

    if (month < 10)
      clock += "0";

    clock += month + "-";

    if (day < 10)
      clock += "0";

    clock += day + " ";
    that.setData({
      nowData: clock
    })
  },
  // 获取当前时间分秒
  CurentTime: function () {
    var that = this;
    var now = new Date();
    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ss = now.getSeconds()           //秒
    var clock = "";
    if (hh < 10)
      clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    that.setData({
      nowtime: clock
    })
  },
  //日期
  bindDateChange: function (e) {
    var date = e.detail.value;
    this.setData({
      date: date
    })
  },
  //bindTimeChange时间
  bindTimeChange: function (e) {
    var time = e.detail.value;
    this.setData({
      time: time
    })
  },
  //预约提交
  formSubmit: function (e) {
    //this.CurentTime();//获取当前时间
    var that = this;
    var pid = that.data.pid;
    if (pid == "" || pid == undefined){
        if (that.data.date == "") {
          var applytime = that.data.nowData + '\t' + that.data.nowtime;
        } else {
          var applytime = that.data.date + '\t' + that.data.time;
        }
    }else{
        if(that.data.date == ""){
          if(that.data.time == ""){
            var applytime = that.data.dates + '\t' + that.data.nowtime;
          }else{
            var applytime = that.data.dates + '\t' + that.data.time;
          }
        }else{
          if (that.data.time == "") {
            var applytime = that.data.date + '\t' + that.data.nowtime;
          } else {
            var applytime = that.data.date + '\t' + that.data.time;
          }
        }
    }
  
    var realname = e.detail.value.realname;
    var phone = e.detail.value.phone;
    var remark = e.detail.value.leave;
    var remark2 = e.detail.value.leave2;
    if (pid == "" || pid == undefined) {
      pid = 0
      if (remark2 == "") {
        wx.showModal({
          title: '提示',
          content: '请输入留言',
          showCancel: false
        })
        return
      } else {
        if (realname == "" || pid == undefined) {
          realname = '小程序'
        }
        if (phone == "" || pid == undefined) {
          phone = '18814450536'
        }
        wx.request({
          url: app.globalData.host + '/api/user/AppointApply',
          method: 'POST',
          data: {
            Uid: app.globalData.userInfo.Uid,
            Pid: pid,
            ApplyTime: applytime,
            RealName: realname,
            Phone: phone,
            Remark: remark2
          },
          success: function (res) {
            if (res.data.Code == 501) {
              wx.showToast({
                title: res.data.Message,
                icon: 'false',
                duration: 2000
              })
              return false;
            } else {
              wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 2000
              })
            }
          },
          fail: function (error) {
            console.log(error)
          }
        })
      }
    } else {
      if (realname == "" || realname == null) {
        wx.showModal({
          title: '提示',
          content: '请填写姓名',
          showCancel: false
        })
        return
      }
      if (remark == "") {
        wx.showModal({
          title: '提示',
          content: '请填写年龄',
          showCancel: false
        })
        return
      }
      if (phone == "") {
        wx.showModal({
          title: '提示',
          content: '请填写手机号',
          showCancel: false
        })
        return
      } else {
        wx.request({
          url: app.globalData.host + '/api/user/AppointApply',
          method: 'POST',
          data: {
            Uid: app.globalData.userInfo.Uid,
            Pid: that.data.pid,
            ApplyTime: applytime,
            RealName: realname,
            Phone: phone,
            Remark: remark + remark2
          },
          success: function (res) {
            if (res.data.Code == 501) {
              wx.showToast({
                title: res.data.Message,
                icon: 'false',
                duration: 2000
              })
              return false;
            } else {
              wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 2000
              })
              var selList = that.getSelList(that.data.cartInfo);
              that.setData({
                selList: selList
              })
              that.createOrder()//订单确认
            }
          },
          fail: function (error) {
            console.log(error)
          }
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.initShippingAddress()//获取地址
    //获取购物车数据
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var cart = that.processImageHost(res.data.Data);

          that.setData({
            saveHidden: true, allSelect: true, noSelect: false, mallName: wx.getStorageSync('mallName'), cartInfo: cart
          });

        }
      }
    })
  },
  getSelList: function (cart) {
    var selList = '';
    var list = cart.StoreCartList[0].CartProductList;
    var cutList = cart.StoreCartList[0].CartFullCutList;
    var suitList = this.data.cartInfo.StoreCartList[0].CartSuitList;
    for (var i = 0; i < list.length; i++) {
      if (list[i].IsSelected) {
        selList += list[i].OrderProductInfo.Type + '_' + list[i].OrderProductInfo.Pid + ','
      }

    }
    for (var i = 0; i < cutList.length; i++) {
      for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
        var curItem = cutList[i].FullCutCartProductList[j];
        if (curItem.IsSelected) {
          selList += curItem.OrderProductInfo.Type + '_' + curItem.OrderProductInfo.Pid + ','
        }
      }
    }
    for (var i = 0; i < suitList.length; i++) {
      var curItem = suitList[i];
      if (curItem.IsSelected) {
        selList += 1 + '_' + curItem.PmId + ','
      }
    }
    if (selList == '') { selList = '_' };
    return selList;
  },
  confirmOrder: function (e) {
    wx.showLoading();
    var that = this;
    var said = 0;
    if (that.data.curAddressData)
      said = that.data.curAddressData.SAId;
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,
      SelList: that.data.selList
    }
    //初始化优惠券
    wx.showLoading();
    wx.request({
      url: app.globalData.host + '/api/order/GetValidCouponList',
      data: {
        selList: that.data.selList,
        uid: app.globalData.userInfo.Uid
      }, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          return;
        }
        that.setData({
          allCoupon: res.data.Data,
          curCoupon: res.data.Data[0]
        });
      }
    })
    //初始化订单
    wx.request({
      url: app.globalData.host + '/api/order/confirmorderv2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0 & that.data.hasPay == false) {
          wx.showModal({
            title: '错误',
            content: res.data.Message,
            showCancel: false
          })
          return;
        }
        that.setData({ hasPay: true });

        //订单确认成功
        var confirm = that.processImageHost(res.data.Data);
        that.setData({
          confirmOrder: confirm
        });
      }
    })

  },
  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetDefaultShipAddress',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: (res) => {
        if (res.data.Code == 0) {
          that.setData({
            curAddressData: res.data.Data
          });
        }
      }
    })
  }
})